package com.w.waiagent.controller.demo.invoke;


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 体验 HTTP 调用示例
 * 对于 SDK 不支持的编程语言或者需要更灵活控制的场景,可以直接使用 HTTP 调用 AI 大模型的API
 * 一般来说,如果有官方的SDK,优先使用SDK;只有在不支持SDK的场景,再使用HTTP调用
 *
 * @author wzp
 * @since 2025/6/8
 */
// 建议dashscope SDK的版本 >= 2.12.0
@Slf4j
@RestController
@RequestMapping("/ali/dashscope/http")
public class ALiDashScopeHttpDemo {

    @Value("${aliyunai.apiKey}")
    private String apiKey;

    @GetMapping("/demo")
    public String demo(@RequestParam("content") String content) {
        String result = callDashScopeApi(content);
        return result;
    }

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    private static final String MODEL_NAME = "qwen-plus";
    private static final String AUTH_HEADER_PREFIX = "Bearer ";

    // 调用 DashScope API
    public String callDashScopeApi(String content) {
        // 构建请求体
        JSONObject requestBody = new JSONObject();
        requestBody.set("model", MODEL_NAME);

        JSONObject input = new JSONObject();
        JSONArray messages = new JSONArray();

        JSONObject systemMessage = new JSONObject();
        systemMessage.set("role", "system");
        systemMessage.set("content", "你是一个乐于助人的助手。");
        messages.add(systemMessage);

        JSONObject userMessage = new JSONObject();
        userMessage.set("role", "user");
        userMessage.set("content", content);
        messages.add(userMessage);

        input.set("messages", messages);
        requestBody.set("input", input);

        JSONObject parameters = new JSONObject();
        parameters.set("result_format", "message");
        requestBody.set("parameters", parameters);

        // 发起 POST 请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", AUTH_HEADER_PREFIX + apiKey)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();

        // 返回响应内容
        return response.body();
    }
}